import { defineStore } from 'pinia';
import axios from '@/plugins/axios';
import { ElMessage } from 'element-plus';

export interface Paper {
  id: number;
  title: string;
  description: string;
  status: 'DRAFT' | 'PUBLISHED';
  createTime: string;
  questionIds: number[];
}

export interface PaperCreateRequest {
  title: string;
  description: string;
  questionIds: number[];
}

export interface PaperUpdateRequest extends PaperCreateRequest {
  id: number;
  status: 'DRAFT' | 'PUBLISHED';
}

export interface PaperSubmissionRequest {
  paperId: number;
  studentId: number;
  answers: { [key: number]: string };
}

export const usePaperStore = defineStore('paper', {
  state: () => ({
    papers: [] as Paper[],
  }),

  actions: {
    // 获取所有试卷
    async fetchPapers() {
      try {
        const response = await axios.get('/api/paper');
        if (response.data.code === 200) {
          this.papers = response.data.data;
          return this.papers;
        }
        throw new Error(response.data.message || '获取试卷列表失败');
      } catch (error: any) {
        ElMessage.error(error.message || '获取试卷列表失败');
        throw error;
      }
    },

    // 根据状态获取试卷
    async fetchPapersByStatus(status: string) {
      try {
        const response = await axios.get(`/api/paper/status/${status}`);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '获取试卷列表失败');
      } catch (error: any) {
        ElMessage.error(error.message || '获取试卷列表失败');
        throw error;
      }
    },

    // 获取单个试卷详情
    async fetchPaperById(id: number) {
      try {
        const response = await axios.get(`/api/paper/${id}`);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '获取试卷详情失败');
      } catch (error: any) {
        ElMessage.error(error.message || '获取试卷详情失败');
        throw error;
      }
    },

    // 创建试卷
    async createPaper(data: PaperCreateRequest) {
      try {
        const response = await axios.post('/api/paper', data);
        if (response.data.code === 200) {
          this.papers.push(response.data.data);
          ElMessage.success('创建试卷成功');
          return response.data.data;
        }
        throw new Error(response.data.message || '创建试卷失败');
      } catch (error: any) {
        ElMessage.error(error.message || '创建试卷失败');
        throw error;
      }
    },

    // 更新试卷
    async updatePaper(data: PaperUpdateRequest) {
      try {
        const response = await axios.put('/api/paper', data);
        if (response.data.code === 200) {
          const index = this.papers.findIndex(p => p.id === data.id);
          if (index !== -1) {
            this.papers[index] = response.data.data;
          }
          ElMessage.success('更新试卷成功');
          return response.data.data;
        }
        throw new Error(response.data.message || '更新试卷失败');
      } catch (error: any) {
        ElMessage.error(error.message || '更新试卷失败');
        throw error;
      }
    },

    // 删除试卷
    async deletePaper(id: number) {
      try {
        const response = await axios.delete(`/api/paper/${id}`);
        if (response.data.code === 200) {
          this.papers = this.papers.filter(p => p.id !== id);
          ElMessage.success('删除试卷成功');
          return response.data.data;
        }
        throw new Error(response.data.message || '删除试卷失败');
      } catch (error: any) {
        ElMessage.error(error.message || '删除试卷失败');
        throw error;
      }
    },

    // 发布试卷
    async publishPaper(id: number) {
      try {
        const response = await axios.post(`/api/paper/publish/${id}`);
        if (response.data.code === 200) {
          const index = this.papers.findIndex(p => p.id === id);
          if (index !== -1) {
            this.papers[index] = response.data.data;
          }
          ElMessage.success('发布试卷成功');
          return response.data.data;
        }
        throw new Error(response.data.message || '发布试卷失败');
      } catch (error: any) {
        ElMessage.error(error.message || '发布试卷失败');
        throw error;
      }
    },

    async submitPaper(data: PaperSubmissionRequest) {
        console.log("00000000");
        try {
        console.log("1111111");
        const response = await axios.post('/api/paper/submit', data);
        console.log("2222222");
        if (response.data.code === 200) {
          console.log("3333333");
          ElMessage.success('试卷提交成功');
          return response.data.data;
        }
        console.log("444444444");
        throw new Error(response.data.message || '试卷提交失败1');
      } catch (error: any) {
        console.error('Submit Error:', error.response?.data || error.message);
        ElMessage.error(error.message || '试卷提交失败2');
        throw error;
      }
    },
  },
});